<template>
  <div v-removeMouseEffect ref="threejsCard">
    <div ref="container" id="container"></div>
  </div>
</template>

<script setup name="ThreejsCard">
import Cookies from 'js-cookie'
import * as THREE from 'three';

import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { onMounted, ref, reactive, toRefs, toRaw } from 'vue';

const threejsCard = ref(null);

onMounted(() => {
  let mixer;

  const clock = new THREE.Clock();
  const container = document.getElementById('container');

  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(300, 200);
  renderer.setClearColor(0xEEEEEE, 0.0);
  renderer.outputEncoding = THREE.sRGBEncoding;
  container.appendChild(renderer.domElement);

  const pmremGenerator = new THREE.PMREMGenerator(renderer);

  const scene = new THREE.Scene();
  scene.environment = pmremGenerator.fromScene(
    new RoomEnvironment(),
    0.04,
  ).texture;

  const camera = new THREE.PerspectiveCamera(
    50,
    268/200,
    1,
    1000,
  );
  camera.position.set(3, 2, 0);

  const controls = new OrbitControls(camera, renderer.domElement);
  controls.target.set(1, 1, 0);
  controls.update();
  controls.enablePan = false;
  controls.enableDamping = true;
  controls.enableZoom = false;

  const dracoLoader = new DRACOLoader();
  dracoLoader.setDecoderPath('js/gltf/');

  const loader = new GLTFLoader();
  loader.setDRACOLoader(dracoLoader);
  loader.load(
    'static/gltf/Flamingo.glb',
    function (gltf) {
      const model = gltf.scene;
      model.position.set(1, 1, 0);
      model.scale.set(0.01, 0.01, 0.01);
      scene.add(model);

      mixer = new THREE.AnimationMixer(model);
      mixer.clipAction(gltf.animations[0]).play();

      animate();
    },
    undefined,
    function (e) {
      console.error(e);
    },
  );
  
  window.onresize = function () {
    camera.aspect = threejsCard.value.offsetWidth / threejsCard.value.offsetHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( threejsCard.value.offsetWidth, threejsCard.value.offsetHeight );
  };

  function animate() {
    requestAnimationFrame(animate);
    const delta = clock.getDelta();
    mixer.update(delta);
    controls.update();
    renderer.render(scene, camera);
  }
});
</script>

<style lang="scss" scoped>
#container:active {
  cursor: move;
}
</style>